package com.zheng.business.web.controller;

import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.common.constant.BusinessResult;
import com.zheng.business.common.constant.BusinessResultConstant;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumptionExample;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaConsumptionService;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.DateUtil;
import com.zheng.common.util.PayCommonUtil;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manage/order")
@Api(value = "业务订单控制器", description = "业务订单控制器")
public class BusinessOrderController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessOrderController.class);

    @Autowired
    private BusinessOrderUmbrellaConsumptionService businessOrderUmbrellaConsumptionService;
    @Value("${api.apicenter.baseUrl}")
    private String baseUrl;
    @Value("${api.apicenter.innercloseBusinessOrderUmbrellaConsumptionUrl}")
    private String innercloseBusinessOrderUmbrellaConsumptionUrl;
    @Value("${api.apicenter.innerFreeBusinessOrderUmbrellaConsumptionUrl}")
    private String innerFreeBusinessOrderUmbrellaConsumptionUrl;


    @Autowired
    private UpmsApiService upmsApiService;
    /**
     * 文章首页
     * @return
     */
    @ApiOperation(value = "业务订单首页")
    @RequiresPermissions("business:order:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/order/index.jsp";
    }


    @ApiOperation(value = "业务订单列表")
    @RequiresPermissions("business:order:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "orderno") String orderno,
            @RequestParam(required = false, defaultValue = "", value = "userid") Integer userid,
            @RequestParam(required = false, defaultValue = "", value = "chipNumber") String chipNumber,
            @RequestParam(required = false, defaultValue = "", value = "begintime") String begintime,
            @RequestParam(required = false, defaultValue = "", value = "endtime") String endtime,
            @RequestParam(required = false, defaultValue = "", value = "status") Integer status,
            @RequestParam(required = false, defaultValue = "", value = "machineId") String machineId,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
        BusinessOrderUmbrellaConsumptionExample example = new BusinessOrderUmbrellaConsumptionExample();
        BusinessOrderUmbrellaConsumptionExample.Criteria criteria = example.createCriteria();
//        List<Integer> status = new ArrayList<Integer>();
//        status.add(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_0);
//        example.createCriteria().andStatusNotIn(status);
        if (StringUtils.isNotBlank(orderno)) {
            criteria.andOrdernoLike("%"+orderno+"%");
        }
        if (StringUtils.isNotBlank(chipNumber)) {
            criteria.andChipNumberEqualTo("%"+chipNumber+"%");
        }

        if (StringUtils.isNotBlank(begintime) && StringUtils.isNotBlank(endtime)) {
            criteria.andCreatetimeBetween(DateUtil.parseDate(begintime,DateUtil.FORMAT_YYYY_MM_DD),DateUtil.parseDate(endtime,DateUtil.FORMAT_YYYY_MM_DD));
        }

        if (userid!=null) {
            criteria.andUseridEqualTo(userid);
        }
        if (StringUtils.isNotBlank(machineId)) {
            criteria.andMachineIdEqualTo(machineId);
        }
        if (status!=null && status!=-1) {
            criteria.andStatusEqualTo(status);
        }
        //代理数据限制
        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
        if(agentId!=null && agentId!= Constant.CONST_SUPER_AGENTID){
            criteria.andAgentidEqualTo(agentId);
        }
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            example.setOrderByClause(sort + " " + order);
        }else{
            example.setOrderByClause("begintime desc");
        }

        List<BusinessOrderUmbrellaConsumption> rows = businessOrderUmbrellaConsumptionService.selectByExampleForOffsetPage(example, offset, limit);
        long total = businessOrderUmbrellaConsumptionService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "结算订单")
    @RequiresPermissions("business:order:close")
    @RequestMapping(value = "/close/{orderno}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public BusinessResult close(@PathVariable("orderno") String orderno,
            @RequestParam(required = false, value = "isCharge") boolean isCharge,
            @RequestParam(required = false, value = "isLoss") boolean isLoss) {
        try{
            BusinessOrderUmbrellaConsumptionExample example = new BusinessOrderUmbrellaConsumptionExample();
            example.createCriteria().andOrdernoEqualTo(orderno);
            BusinessOrderUmbrellaConsumption consumption = businessOrderUmbrellaConsumptionService.selectFirstByExample(example);
            //
            boolean needClose = false;
            //状态为已借出、还伞失败、还伞成功且待结算才需要结算
            if(consumption!=null && (consumption.getStatus()==BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3 ||
                    consumption.getStatus()==BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4 ||
                    consumption.getStatus()==BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5)){
                needClose = true;
            }
            if(needClose){
                String url = baseUrl + innercloseBusinessOrderUmbrellaConsumptionUrl + "?orderNo=" + orderno +"&isCharge=" + isCharge + "&isLoss=" + isLoss;
                String result = PayCommonUtil.call4Post(url);
                if ("SUCCESS".equals(result)) {
                    return new BusinessResult(BusinessResultConstant.SUCCESS, "订单结算提交完成");
                }else{
                    return new BusinessResult(BusinessResultConstant.FAILED,"订单结算异常");
                }
            }else{
                return new BusinessResult(BusinessResultConstant.FAILED,"订单无需结算");
            }
        }catch (Exception e){
            return new BusinessResult(BusinessResultConstant.FAILED,"订单结算异常");
        }
    }
    @ApiOperation(value = "结算订单")
    @RequiresPermissions("business:order:free")
    @RequestMapping(value = "/free/{orderno}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public BusinessResult free(@PathVariable("orderno") String orderno) {
        try{
            BusinessOrderUmbrellaConsumptionExample example = new BusinessOrderUmbrellaConsumptionExample();
            example.createCriteria().andOrdernoEqualTo(orderno);
            BusinessOrderUmbrellaConsumption consumption = businessOrderUmbrellaConsumptionService.selectFirstByExample(example);
            //
            boolean needFree = false;
            //状态为交易完成且归还时间为7天内的订单才能提交免单
            if(consumption!=null && consumption.getEndtime()!=null && (
                    consumption.getStatus()==BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6
                            && DateUtil.getDateIntervalDay(DateUtil.getDate(),consumption.getEndtime())<=7
                    )
             ){
                needFree = true;
            }
            if(needFree){
                String url = baseUrl + innerFreeBusinessOrderUmbrellaConsumptionUrl + "?orderNo=" + orderno ;
                String result = PayCommonUtil.call4Post(url);
                if ("SUCCESS".equals(result)) {
                    return new BusinessResult(BusinessResultConstant.SUCCESS, "免单提交完成");
                }else{
                    return new BusinessResult(BusinessResultConstant.FAILED,"免单异常");
                }
            }else{
                return new BusinessResult(BusinessResultConstant.FAILED,"订单不符合免单规则【需归还时间7天内】");
            }
        }catch (Exception e){
            return new BusinessResult(BusinessResultConstant.FAILED,"免单异常");
        }
    }
}